package com.party.admin.web.controller.photo;

import com.google.common.base.Strings;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.photo.AlbumBizService;
import com.party.admin.biz.photo.PhotoBizService;
import com.party.admin.biz.photo.PhotoProjectBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.circle.CircleInput;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.circle.Circle;
import com.party.core.model.circle.CircleTag;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.ThirdMember;
import com.party.core.model.photo.*;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.circle.ICircleService;
import com.party.core.service.circle.ICircleTagService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IThirdMemberService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.photo.IPhotosImgInfoService;
import com.party.core.service.photo.IPhotosTagService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 活动相册管理
 *
 * @author haugnwuming
 *         on 2018/5/30
 */
@Controller
@RequestMapping(value = "/photo/photoproject")
public class PhotoController {

    @Autowired
    private IPhotoProjectService photoProjectService;
    @Autowired
    private ICircleService circleService;
    @Autowired
    private ICircleTagService circleTagService;

    @Autowired
    private IPhotosImgInfoService photosImgInfoService;

    @Autowired
    private AlbumBizService albumBizService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private IPhotosTagService photosTagService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private PhotoProjectBizService photoProjectBizService;
    @Autowired
    private IThirdMemberService thirdMemberService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private PhotoBizService photoBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 相册列表
     *
     * @param photoProject
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView goodsOrderList(PhotoProject photoProject, Page page, CommonInput commonInput ,
                                       String projectName , String member,Integer softType) {
        final String pattern = "yyyy-MM-dd";
        ModelAndView mv = new ModelAndView("photo/projectList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        params.put("name",projectName);
        params.put("member",member);
        params.put("softType",softType);
        List<PhotoProject> photoProjectList = photoProjectService.webListPage(params, page);

        List<PhotoProjectOutput> outputList = LangUtils.transform(photoProjectList, input -> {
            PhotoProjectOutput output = PhotoProjectOutput.transform(input);
            if (StringUtils.isNotEmpty(input.getCircleId())) {
                Circle circle = circleService.get(input.getCircleId());
                if(circle != null) {
                    output.setCircleName(circle.getName());
                }
            }
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "photo");
            String url = cosBizService.getPreviewPictureUrl(filePath + input.getId());
            output.setQrcodeUrl(url);
            return output;
        });

        if (null != params.get("startDate")) {
            commonInput.setCreateStart(params.get("startDate").toString().substring(0, pattern.length()));
        }
        if (null != params.get("endDate")) {
            commonInput.setCreateEnd(params.get("endDate").toString().substring(0, pattern.length()));
        }

        // List<PhotoProject> photoProjectList = photoProjectService.list(photoProject);
        mv.addObject("projectList", outputList);
        mv.addObject("input", commonInput);
        mv.addObject("projectName", projectName);
        mv.addObject("softType", softType);
        mv.addObject("member", member);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 删除相册
     *
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String projectId) {
        PhotosTag param = new PhotosTag();
        param.setPhotosId(projectId);
        param.setType(PhotosTag.TYPE_CUSTOM);
        List<PhotosTag> tags = photosTagService.list(param);

        if (CollectionUtils.isNotEmpty(tags)) {
            return AjaxResult.error("该相册项目下已有自定义分类, 不能删除");
        }

        PhotosImgInfo imgInfo = new PhotosImgInfo();
        imgInfo.setPhotosId(projectId);
        Page page = new Page(1, 1);
        List<PhotosImgInfo> imgs = photosImgInfoService.listPage(imgInfo, page);

        if (CollectionUtils.isNotEmpty(imgs)) {
            return AjaxResult.error("该相册项目下已有图片, 不能删除");
        }

        boolean result = photoProjectBizService.deletePhotoBiz(projectId);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 相册编辑
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "toForm")
    public ModelAndView toForm(PhotoProject photoProject) {
        ModelAndView mv = new ModelAndView("photo/publishPhotoProject");
        String projectId = photoProject.getId();
        String circleId = photoProject.getCircleId();
        if (StringUtils.isNotEmpty(circleId)) {
            Circle circle = circleService.get(circleId);
            CircleTag circleTag = new CircleTag();
            circleTag.setCircle(circleId);
            List<CircleTag> circleTagList = circleTagService.list(circleTag);
            mv.addObject("circle", circle);
            mv.addObject("circleId", circle.getId());
            mv.addObject("memberId", circle.getCreateBy());
            mv.addObject("ctList", circleTagList);
            mv.addObject("noTypeIsOperate", circle.getNoTypeIsOperate());
        }
        if (!Strings.isNullOrEmpty(projectId)) {
            CircleTag circleTag = new CircleTag();
            PhotoProject project = photoProjectService.get(projectId);
            MemberGroup member = memberGroupService.get(project.getMemberId());
            project.setMemberName(member.getRealname());
            circleTag.setCircle(project.getCircleId());
            List<CircleTag> circleTagList = circleTagService.list(circleTag);
            Integer noTypeIsOperate = null;
            if (StringUtils.isNotEmpty(project.getCircleId())) {
                Circle circle = circleService.get(project.getCircleId());
                if (null != circle) {
                    noTypeIsOperate = circle.getNoTypeIsOperate();
                }
            }
            ThirdMember thirdMember = thirdMemberService.findByTargetId(project.getId());
            mv.addObject("thirdMember", thirdMember);

            mv.addObject("noTypeIsOperate", noTypeIsOperate);
            mv.addObject("project", project);
            mv.addObject("circleId", project.getCircleId());
            mv.addObject("memberId", project.getMemberId());
            mv.addObject("ctList", circleTagList);
        }
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(PhotoProject photoProject, PhotoInput input, CircleInput circleInput,ThirdMember thirdMember) {
        try {
            photoProject.setIntroduction(photoProject.getIntroduction().trim());
            if (StringUtils.isNotEmpty(input.getStartDate())) {
                photoProject.setStartTime(DateUtils.parse(input.getStartDate()));
            }
            if (StringUtils.isNotEmpty(input.getEndDate())) {
                photoProject.setEndTime(DateUtils.parse(input.getEndDate()));
            }
            if (circleInput.getCircleTags() != null) {
                for (CircleTag circleTag : circleInput.getCircleTags()) {
                    CircleTag t = circleTagService.get(circleTag.getId());
                    if(photoProject.getOperatePermission() == 1) {
                        t.setIsOperate(circleTag.getIsOperate());
                    }
                    if(photoProject.getOperatePermission() == 0) {
                        t.setIsOperate(1);
                    }
                    circleTagService.update(t);
                }
            }
            if (Strings.isNullOrEmpty(photoProject.getId())) {
                photoProjectService.insert(photoProject);
                // 初始化系统标签
                albumBizService.initTags(photoProject.getId());
            } else {
                photoProjectService.update(photoProject);
            }

            // 如果从圈子来的, 更新圈子的no_type_is_operate字段
            if (StringUtils.isNotEmpty(photoProject.getCircleId()) && null != circleInput.getNoTypeIsOperate()) {
                Circle circle = circleService.get(photoProject.getCircleId());
                circle.setNoTypeIsOperate(circleInput.getNoTypeIsOperate());
                circleService.update(circle);
            }
            try {
                WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_PHOTO);
                XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
                qrCodeRequest.setPage("pages/photo/index");
                qrCodeRequest.setScene(photoProject.getId());
                String filePath = fileBizService.getUploadCIPath(photoProject.getMemberId(), "photo");
                fileBizService.uploadCloudOut(photoProject.getId(), filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
            } catch (Exception e) {
                logger.error("生成小程序码异常", e);
            }

            //维护第三方用户
            if (photoProject.getEditShare() != null) {
                if (photoProject.getEditShare() == 1) {
                    ThirdMember unique = thirdMemberService.findByTargetId(photoProject.getId());
                    if (unique == null) {
                        unique = new ThirdMember();
                        MyBeanUtils.copyBeanNotNull2Bean(thirdMember, unique);
                        unique.setId(null);
                        unique.setPublisher(photoProject.getMemberId());
                        unique.setMemberType(ThirdMember.THIRD_MEMBER_TYPE_PHOTO);
                        unique.setTargetId(photoProject.getId());
                        thirdMemberService.insert(unique);
                    } else {
                        if (!thirdMember.getAccount().equals(unique.getAccount())) {
                            unique.setAccount(thirdMember.getAccount());
                            unique.setPassword(thirdMember.getPassword());
                            thirdMemberService.update(unique);
                        }
                    }
                    List<String> uriAll = thirdMemberService.allURI();
                    stringJedis.setValue("thirdMemberList", uriAll.toString());

                } else if (photoProject.getEditShare() == 0) {
                    thirdMemberService.deleteByTargetId(photoProject.getId());
                }
            }
        } catch (Exception e) {
            return AjaxResult.error("");
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping("checkXcxQrCode")
    public AjaxResult checkXcxQrCode(String photoId) {
        if (StringUtils.isEmpty(photoId)) {
            return AjaxResult.error("相册id不能为空");
        }
        try {
            WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_PHOTO);
            PhotoProject photoProject = photoProjectService.get(photoId);
            String filePath = fileBizService.getUploadCIPath(photoProject.getMemberId(), "photo");
            XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
            qrCodeRequest.setPage("pages/photo/index");
            qrCodeRequest.setScene(photoProject.getId());
            String result = fileBizService.uploadCloudOut(photoProject.getId(), filePath,
                    qrCodeRequest, openMember.getAuthorizerAccessToken(), 0);
            if (StringUtils.isEmpty(result)) {
                throw new Exception("生成小程序码异常");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("生成小程序码异常", e);
            return AjaxResult.error("异常");
        }
    }

    /**
     * 生成分享相关信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("generateInfo")
    public AjaxResult generateInfo(String id) {
        Map<String, Object> result = photoBizService.generateInfo(id);
        return AjaxResult.success(result);
    }

}
